/**
 * 
 */
package com.noahsloan.nutils.streams.clocked;

import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

public class ClockTimer {

    public static final long TICK = Long.getLong("n-utils.clock-timer.tick",
            250);

    private static final ClockTimer instance = new ClockTimer(TICK);

    private final Timer timer;

    private Set<Clocked> list;

    private ClockTimer(final long period) {
        super();
        this.list = new HashSet<Clocked>();
        this.timer = new Timer(true);
        this.timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                synchronized (ClockTimer.instance) {
                    for (Clocked c : list) {
                        c.heartbeat();
                    }
                }
            }
        }, period, period);
    }

    public synchronized void register(Clocked c) {
        this.list.add(c);
    }

    public synchronized void unregister(Clocked c) {
        list.remove(c);
    }

    public static ClockTimer getInstance() {
        return instance;
    }

    /**
     * Adapts the ClockTimer into a {@link TimeSource}.
     * 
     * @author noah
     * 
     */
    public static class DefaultTimeSource implements TimeSource {

        public long currentTime() {
            return System.currentTimeMillis();
        }

        public void register(Clocked clocked) {
            instance.register(clocked);
        }

        public void unregister(Clocked clocked) {
            instance.unregister(clocked);
        }

        public long getTick() {
            return TICK;
        }
    }
}